package com.hiwhitley.datastructure;

import java.util.Stack;

/**
 * Created by hiwhitley on 2017/4/14.
 */
public class BalanceChecker {
    public static boolean checkBalance(String expression) {
        Stack<Character> openStack = new Stack<>();
        boolean isBalanced = true;
        char next;
        int len = expression.length();

        for (int i = 0; isBalanced && (i < len); i++) {
            next = expression.charAt(i);
            switch (next) {
                case '(':
                case '[':
                case '{':
                    openStack.push(next);
                    break;
                case ')':
                case ']':
                case '}':
                    if (openStack.isEmpty()) {
                        isBalanced = false;
                    } else {
                        char open = openStack.pop();
                        isBalanced = isPaired(open, next);

                    }
                    break;
                default:
                    break;
            }
        }

        if (!openStack.isEmpty()) {
            isBalanced = false;
        }
        return isBalanced;
    }

    private static boolean isPaired(char open, char next) {
        return (open == '(' && next == ')')
                || (open == '[' && next == ']')
                || (open == '{' && next == '}');
    }
}
